<?php

namespace App\common\OutPay;

use App\Admin\Services\InPayService;
use App\Admin\Services\OutPayService;
use App\Models\PayExchange\ExchangeListModel;
use App\utility\HttpHelper;
use Illuminate\Support\Facades\Log;

class SafePay extends Base
{
    public function pay(ExchangeListModel $model)
    {

        $params = [
            "acc_code" => 'PH_GCASH',
            "acc_name" => "LILAILAI",
            "acc_no" => $model->gcash_num,
            "currency" => "PHP",
            "mer_no" => $this->config['mer_no'],
            "method" => "fund.apply",
            "order_amount" => (string)$model->amount,
            "order_no" => $model->order_no,
            "province" => "Metro Manila",
            "returnurl" => $this->config['notify'],
        ];
        $params['sign'] = $this->sign($params);
        \App\common\Log::write('safepay代付请求响应：' . json_encode($params), 'outPay', 'outPay');
        $retJson = HttpHelper::post($this->config['url'], json_encode($params));
        $ret = json_decode($retJson, true);
        \App\common\Log::write('safepay代付请求响应：' . $retJson, 'outPay', 'outPay');
//        Log::info('safepay:---代付请求'.$retJson);
        if ($ret && $ret['status'] == 'success') {
            return true;
        }
        $this->err = $ret['status_mes'] ?? $retJson;
        return false;

    }

    public function notify(array $params)
    {
        $sign = $params['sign'];
        \App\common\Log::write('safepay代付回调响应：' . json_encode($params), 'outPay', 'outPay');
        unset($params['sign'], $params['s'], $params['result_mes']);
        $curSign = $this->sign($params);
        if ($sign != $curSign) {
            $this->err = 'sign err';
            return false;
        }
        $order = $this->orderInfo($params['order_no']);
        if ($order === false) {
            return false;
        }
        if ($params['result'] == 'success') {//成功
            $data['order_id'] = $order->order_no;
            $data['league_id'] = $order->league_id;
            $data['user_id'] = $order->user_id;
            $data['result'] = 0;
            return OutPayService::NotifyWebServer($data);
        } else {//失败
            $data['order_id'] = $order->order_no;
            $data['league_id'] = $order->league_id;
            $data['user_id'] = $order->user_id;
            $data['result'] = 1;
            return OutPayService::NotifyWebServerError($data);
        }

    }


    public function sign($data)
    {
        ksort($data);
        $str = '';
        foreach ($data as $key => $val) {
            if (!$val) continue;
            $str .= $key . '=' . $val . '&';
        }
        $str = substr($str, 0, strlen($str) - 1);
        $str .= $this->config['key'];
        return strtolower(md5($str));
    }

}